//
//  ProductViewController.m
//  AppMua5
//
//  Created by duong nguyen on 9/13/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ProductViewController.h"

@interface ProductViewController ()

@end

@implementation ProductViewController
@synthesize viewApi,headerBelow,productTableview;
@synthesize muaApi,requestData,productList,indicatorView,rightButtonItem;
@synthesize isGetListProductByCategory,commonApi;

-(id)init{
    [super init];
    self.muaApi=[[MuaAPI alloc]init];
    viewApi=[[ViewApi alloc]init];
    headerBelow=[[UIView alloc]init];
    productTableview=[[UITableView alloc]init];
    productList=[[NSMutableArray alloc]init];
    commonApi=[[CommonAPI alloc]init];
    // Bat dau la load danh sach san pham theo category.
    isGetListProductByCategory=true;
    return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void) initProductView{
    
    // Add product Table view below the header and set delegate
    [viewApi getCustomTableView:self.productTableview];
    self.productTableview.dataSource=self;
    self.productTableview.delegate=self;
    [self.view addSubview:self.productTableview];
    
    // Init indicatorView
    [self initIndicatorView];
    
}

// Init IndicatorView
-(void) initIndicatorView{
    self.indicatorView=[[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    self.rightButtonItem=[[UIBarButtonItem alloc]initWithCustomView:indicatorView];
    [indicatorView setColor:[UIColor grayColor]];
    self.navigationItem.rightBarButtonItem=self.rightButtonItem;
}

-(void)loadView{
    [super loadView];
    // Khoi tao view cho PorductViewController.
    [self initProductView];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    // Load data here.
    [self getProductListByCategory:12];
}

-(void)viewDidAppear:(BOOL)animated{
    [viewApi getCustomNavigationBarFrame:self.navigationController.navigationBar];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return YES;
}

#pragma Here for requests

-(void) getProductListByCategory:(NSInteger)categoryId{
    [indicatorView startAnimating];
    [muaApi getListProductByCategory:categoryId context:self];
}

-(void) getListProductByShop:(NSInteger)userId shopObject:(ShopObject *)shop{
    [indicatorView startAnimating];
    [muaApi getListProductByShop:userId shopObject:shop context:self];
}

-(void) requestFinished:(ASIHTTPRequest *)request{
    
    NSString *response=[request responseString];
    [self.productList addObjectsFromArray:[muaApi parseListProductByCategory:response]];
    // Stop aniamte
    [indicatorView stopAnimating];
    // Reload data table when request finished
    [self.productTableview reloadData];
    
    response=nil;
    [response release];
}

-(void) requestFailed:(ASIHTTPRequest *)request{
    NSError *error=[request error];
    NSLog(@"Product request::%@",error);
    [indicatorView stopAnimating];
}

# pragma Add UITableView delegate and UITableView datasource

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.productList.count;
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    // Khai bao Product Object de chua thong tin hien thi len cell
    ProductObject *product=[[ProductObject alloc]init];
    product=[self.productList objectAtIndex:indexPath.row];
    if (product==nil) {
        return nil;
    }
    static NSString *CellIdentifier = @"Cell";
    ShopMuaCell *cell=[[ShopMuaCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    
    cell=[[ShopMuaCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    
//    [cell.shopName setText:[product.shop.shopName uppercaseString]];
    
    NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:product.productImage]];
    if (data!=nil) {
        [cell.productImageView setImage:[UIImage imageWithData:data]];
    }else {
        [cell.productImageView setImage:[UIImage imageNamed:@"iphone.jpg"]];
    }
    
    [cell.productName setText:[product.productName uppercaseString]];
   
    
    [cell.productPrice setText:[NSString stringWithFormat:@"%@đ",[commonApi translateMoneyToTextFormat: product.productPrice]]];
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    // Configure the view for the selected state
    cell.shopName.tag=indexPath.row;
    
    // Khi click vao shop name
//    UITapGestureRecognizer *tapGetsture=[[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapShopName:) ]autorelease];
//    [cell.shopName addGestureRecognizer:tapGetsture];
    
    data=nil;
    [data release];
    return cell;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    int indexRow=indexPath.row;
    ProductObject *product=[self.productList objectAtIndex:indexRow];
    if(product!=nil){
        ProductDetailViewController *detail=[[ProductDetailViewController alloc]init];
        [detail setProductObject:product];
        [self.navigationController pushViewController:detail animated:YES];
    
        product=nil;
        [product release];
        [detail release];
    }
}

#pragma Scroll delegate
// Will load more when go 2/3 the table's height
-(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    int count=self.productList.count;
    int position=scrollView.contentOffset.y/320;
    float temp=(float)position/count;
    if (temp>=(MORE_PRODUCT)) {
        [self.indicatorView startAnimating];
        // Load more
        [self getProductListByCategory:12];
    }

}
-(void) dealloc{
    
    [headerBelow release];
    [productTableView release];
    [muaApi release];
    [viewApi release];
    [requestData release];
    [productList release];
    [super dealloc];
}
@end
